package com.fjh.springboot_01.controller;

import com.fjh.springboot_01.pojo.Result;
import com.fjh.springboot_01.pojo.TeacherInfo;
import com.fjh.springboot_01.pojo.User;
import com.fjh.springboot_01.service.TeacherInfoService;
import com.fjh.springboot_01.service.UserService;
import com.fjh.springboot_01.utils.AliOssUtil;
import com.fjh.springboot_01.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teacher")
public class TeacherInfoController {
    @Autowired
    private TeacherInfoService teacherInfoService;

    @Autowired
    private UserService userService;

    @PostMapping("/upload-document")
    public Result<String> uploadDocument(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String url = AliOssUtil.uploadFile(originalFilename, file.getInputStream());
        return Result.success(url);
    }

    @PostMapping("/submit-info")
    public Result<String> submitTeacherInfo(@RequestBody TeacherInfo teacherInfo) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        
        // 检查用户是否是教师（通过查询用户信息）
        User user = userService.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 如果用户注册为教师但当前以学生身份登录，也允许提交认证
        if (user.getRole() != 1) {
            return Result.error("只有教师用户可以提交认证信息");
        }

        teacherInfo.setUserId(userId);
        
        try {
            teacherInfoService.submitTeacherInfo(teacherInfo);
            // 更新用户状态为待审核
            userService.handleTeacherApproval(userId, 0);
            return Result.success("教师认证信息提交成功，等待审核");
        } catch (Exception e) {
            return Result.error("提交失败：" + e.getMessage());
        }
    }

    @GetMapping("/info")
    public Result<TeacherInfo> getTeacherInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        
        TeacherInfo teacherInfo = teacherInfoService.getTeacherInfo(userId);
        if (teacherInfo == null) {
            // 返回空对象而不是错误，并初始化基本属性
            teacherInfo = new TeacherInfo();
            teacherInfo.setUserId(userId);
            teacherInfo.setSubjects(""); // 初始化为空字符串，避免前端split错误
            return Result.success(teacherInfo);
        }
        return Result.success(teacherInfo);
    }

    @GetMapping("/info/{userId}")
    public Result<TeacherInfo> getTeacherInfoById(@PathVariable Integer userId) {
        // 验证当前用户是否是管理员
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer role = (Integer) map.get("role");
        if (role != 2) {
            return Result.error("无权限访问");
        }

        TeacherInfo teacherInfo = teacherInfoService.getTeacherInfo(userId);
        // 如果未找到教师信息，返回空对象而不是null
        if (teacherInfo == null) {
            teacherInfo = new TeacherInfo();
            teacherInfo.setUserId(userId);
            teacherInfo.setSubjects(""); 
        }
        return Result.success(teacherInfo);
    }

    @GetMapping("/all")
    public Result<List<TeacherInfo>> getAllTeacherInfo() {
        // 验证当前用户是否是管理员
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer role = (Integer) map.get("role");
        if (role != 2) {
            return Result.error("无权限访问");
        }

        List<TeacherInfo> teacherInfoList = teacherInfoService.getAllTeacherInfo();
        return Result.success(teacherInfoList != null ? teacherInfoList : new ArrayList<>());
    }

    @PutMapping("/update")
    public Result<String> updateTeacherInfo(@RequestBody TeacherInfo teacherInfo) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        
        // 检查用户是否是教师（通过查询用户信息）
        User user = userService.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 如果用户注册为教师但当前以学生身份登录，也允许更新认证
        if (user.getRole() != 1) {
            return Result.error("只有教师用户可以更新认证信息");
        }

        teacherInfo.setUserId(userId);
        
        try {
            teacherInfoService.updateTeacherInfo(teacherInfo);
            // 更新用户状态为待审核
            userService.handleTeacherApproval(userId, 0);
            return Result.success("教师认证信息更新成功，等待审核");
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }
} 